<template>
    <div class="app-container">
      <div class="filter-container">
                          <el-input v-model="listQuery.condition.userName" size="small" text="用户名称" placeholder="用户名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
                  <el-input v-model="listQuery.condition.userAccount" size="small" text="登陆账号" placeholder="登陆账号" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
        <el-button v-waves class="filter-item" size="small" type="primary"   @click="handleFilter">
          查询
        </el-button>
        <el-button class="filter-item" size="small" style="margin-left: 10px;" type="primary" @click="handleCreate">
          新增
        </el-button>
        <el-button class="filter-item" title="请勾选需要删除的数据" :disabled="deleteStatus" type="danger" style="margin-left: 10px;" size="small" @click="handleDelete">
          删除
        </el-button>
      </div>

      <el-table
        :data="tableData"
        border
        v-loading="listLoading"
        :height="tableHeight"
        header-row-class-name="table-header-background"
        @selection-change="handleSelectionChange"
        style="width: 100%">
          <el-table-column
            type="selection"
            width="35">
          </el-table-column>
          <el-table-column
                  prop="userName"
                  label="用户名称"
                  width="150">
          </el-table-column>
          <el-table-column
                  prop="userAccount"
                  label="登陆账号"
                  width="150">
          </el-table-column>
          <el-table-column
            prop="password"
            label="密码"
            width="150">
          </el-table-column>
          <el-table-column
                  prop="avatar"
                  label="头像"
                  width="150">
          </el-table-column>
          <el-table-column
                  prop="sex"
                  label="性别"
                  width="150">
          </el-table-column>
          <el-table-column
                  prop="email"
                  label="邮件"
                  width="150">
          </el-table-column>
          <el-table-column
                  prop="phone"
                  label="电话"
                  width="150">
          </el-table-column>
          <el-table-column
                  prop="description"
                  label="备注"
                  width="150">
          </el-table-column>
          <el-table-column
                  prop="valid"
                  label="是否有效"
                  width="150">
          </el-table-column>
        <el-table-column label="操作" align="center" width="350" fixed="right" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button type="primary" size="mini" @click="handleUpdate(row)">
              编辑
            </el-button>
            <el-button type="warning" size="mini" @click="handleAllocateRole(row)">
              分配角色
            </el-button>
            <el-button v-if="row.valid == 0" size="mini" type="success" @click="handleModifyStatus(row, 1)">
              启用
            </el-button>
            <el-button v-if="row.valid == 1" size="mini" @click="handleModifyStatus(row, 0)">
              禁用
            </el-button>
            <el-button size="mini" type="primary" @click="handleResetAuth(row)">
              重置密码
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

      <el-dialog title="新增"  :visible.sync="dialogFormVisible">
        <el-form ref="dataForm" :rules="rules" :model="tempData" label-position="right" label-width="100px" style="width: 400px; margin-left:50px;">
              <el-form-item label="用户名称" prop="userName">
                <el-input v-model="tempData.userName" placeholder="请输入用户名称" />
              </el-form-item>
              <el-form-item label="登陆账号" prop="userAccount">
                <el-input v-model="tempData.userAccount" placeholder="请输入登陆账号" :readOnly="optionFlag === 'update'" />
              </el-form-item>
              <el-form-item label="备注" prop="description">
                <el-input v-model="tempData.description" placeholder="请输入备注" />
              </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="optionFlag === 'add' ? createData() : (optionFlag === 'update' ? updateData() : null)">
            确认
          </el-button>
        </div>
      </el-dialog>


      <el-dialog title="分配角色"  width="500px" :visible.sync="dialogAllocateRoleFormVisible">
        <el-form :model="upmsUserRole" label-width="80px" label-position="left">
          <el-form-item label="角色">
            <el-tree
              ref="tree"
              :data="userRoles"
              :props="defaultProps"
              node-key="id"
              show-checkbox
              default-expand-all
              highlight-current
              :default-checked-keys="upmsUserRole.roleIdList"
              :check-on-click-node="true"
            />
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogAllocatePermissionFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="doAllocateRole()">
            确认
          </el-button>
        </div>
      </el-dialog>

    </div>

</template>


<script>

    import { listUpmsUser, addUpmsUser, editUpmsUser, batchDelUpmsUser, resetUpmsUserAuth } from '@/api/upms/user/index'
    import { treeRoleByUserId, allocateRole } from '@/api/upms/userRole/index'

    import waves from '@/directive/waves' // waves directive
    import Pagination from '@/components/Pagination' // secondary package based on el-pagination
    import { Message } from 'element-ui'


    export default {
        name: "index.vue"
      , components: { Pagination,allocateRole }
      ,  directives: { waves }
      , data() {
        return {
          defaultProps: {
            children: 'children',
            label: 'label'
          },
          total: 0,
          userRoles:[],
          upmsUserRole:{
            upmsUserId:null,
            roleIdList:[]
          },
          deleteStatus:true,
          tableHeight: window.innerHeight - 205,
          tableData: null,
          listLoading: true,
          optionFlag: null,
          listQuery: {
            page: 1,
            limit: 20,
            condition: {
                userName:null,
                userAccount:null,
                password:null,
                avatar:null,
                salt:null,
                sex:null,
                email:null,
                phone:null,
                upmsDepartmentId:null,
                description:null,
                valid:null,
                deleted:null,
                version:null,
                createTime:null,
                updateTime:null,
                createUser:null,
                updateUser:null,
            }
          },
          dialogFormVisible:false, // 是否显示模态框
          dialogAllocatePermissionFormVisible:false,
          rules: {
            userName: [{ required: true, message: '用户名称不能为空', trigger: 'change' }],
            userAccount: [{ required: true, message: '登陆账号不能为空', trigger: 'change' }]
          },
          tempData:{
            userName:null,
            userAccount:null,
            password:null,
            avatar:null,
            salt:null,
            sex:null,
            email:null,
            phone:null,
            upmsDepartmentId:null,
            description:null,
            valid:null,
            deleted:null,
            version:null,
            createTime:null,
            updateTime:null,
            createUser:null,
            updateUser:null,
          },
          multipleSelection: []
        }
      }
      , created() {
        this.getList()
      }
      , methods : {
        handleFilter() {
          this.getList();
        }
        , handleCreate() {
          this.resetTemp()
          this.dialogFormVisible = true
          this.optionFlag = "add"
          this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
          })
        }
        , handleUpdate(row) {
          this.optionFlag = "update"
          this.tempData = Object.assign({}, row) // copy obj
          this.dialogFormVisible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
          })
        }
        , handleAllocateRole(row) {
          this.upmsUserRole.upmsUserId = row.id;
          treeRoleByUserId({upmsUserId:row.id}).then(response => {
            this.dialogAllocateRoleFormVisible = true;
            if (response.result) {
              this.userRoles = response.data.treeNode.children;
              this.upmsUserRole.roleIdList = response.data.checkedKeys;
            }
          })
        }
        , handleDelete() {
          this.$confirm('此操作将永久删除选中的无效用户数据, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let idList = [];
            this.multipleSelection.forEach(function (value) {
              idList.push(value.id);
            });
            batchDelUpmsUser({idList:idList}).then(response => {
              if (response.result) {
                Message({
                  message: response.msg,
                  type: 'success',
                  duration: 5 * 1000
                })
              }
              this.getList();
            })
          }).catch(() => {

          });

        }
        , resetTemp() {
          this.tempData = {
          userName:null,
          userAccount:null,
          password:null,
          avatar:null,
          salt:null,
          sex:null,
          email:null,
          phone:null,
          upmsDepartmentId:null,
          description:null,
          valid:null,
          deleted:null,
          version:null,
          createTime:null,
          updateTime:null,
          createUser:null,
          updateUser:null,
          }
          this.optionFlag = null
        }
        , createData() {
          this.$refs['dataForm'].validate((valid) => {
            if (valid) {
              addUpmsUser(this.tempData).then(response => {
                this.dialogFormVisible = false
                if (response.result) {
                  Message({
                    message: response.msg,
                    type: 'success',
                    duration: 5 * 1000
                  })
                }
                this.getList();
              })
            }
          })
        }
        , updateData() {
          this.$refs['dataForm'].validate((valid) => {
            if (valid) {
              editUpmsUser(this.tempData).then(response => {
                this.dialogFormVisible = false
                if (response.result) {
                  Message({
                    message: response.msg,
                    type: 'success',
                    duration: 5 * 1000
                  })
                }
                this.getList();
              })
            }
          })
        }
        , handleResetAuth(row) {
          this.$prompt('请输入重置密码', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputPattern: /[0-9a-zA-Z]/g,
            inputErrorMessage: '密码只能输入字母或数字'
          }).then(({ value }) => {
            resetUpmsUserAuth({
              id:row.id,
              version:row.version,
              password:value
            }).then(response => {
              if (response.result) {
                Message({
                  message: response.msg,
                  type: 'success',
                  duration: 5 * 1000
                })
              }
              this.getList()
            })
          }).catch(() => {
          });
        }
        , handleModifyStatus(row, valid) {
          let updateUpmsUser = {
            id : row.id,
            version:row.version,
            valid : valid
          }
          editUpmsUser(updateUpmsUser).then(response => {
            if (response.result) {
              Message({
                message: response.msg,
                type: 'success',
                duration: 5 * 1000
              })
            }
            this.getList();
          })

        }
        , getList() {
          this.listLoading = true
          listUpmsUser(this.listQuery).then(response => {
            this.tableData = response.data.data
            this.total = response.data.total

            setTimeout(() => {
              this.listLoading = false
            }, 0.5 * 1000)
          })
        }
        , handleSelectionChange(row) {
          if (row && row.length > 0) {
            this.deleteStatus=false;
            this.multipleSelection = row;
          } else {
            this.deleteStatus=true;
          }
        }
        , doAllocateRole() {
          const checkedKeys = this.$refs.tree.getCheckedKeys();
          this.upmsUserRole.roleIdList = checkedKeys;
          allocateRole(this.upmsUserRole).then(response => {
            if (response.result) {
              Message({
                message: response.msg,
                type: 'success',
                duration: 5 * 1000
              })
            }
            this.dialogAllocateRoleFormVisible=false;
            this.upmsUserRole = {};
          })
        }
      }
    }
</script>

<style scoped>

</style>
